<template>
    <div id="app">
        <div>
            <span>姓名:</span>
            <input type="text" v-model.trim.lazy="name" />
        </div>
        <div>
            <span>年龄:</span>
            <input type="number" v-model.number="age" />
        </div>
        <div>
            <span>性别:</span>
            <select v-model="sex">
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
        </div>
        <div>
            <button @click="addOrEdit">添加/修改</button>
        </div>
        <div>
            <table border="1" cellpadding="10" cellspacing="0">
                <tr>
                    <th>序号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
                <tr v-for="obj,index in arr" :key="index">
                    <td>{{index+1}}</td>
                    <td>{{obj.name}} </td>
                    <td>{{obj.age}} </td>
                    <td>{{obj.sex}} </td>
                    <td>
                        <button @click="del(index)">删除</button>
                        <button @click="edit(index)">编辑</button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                name: '',
                age: '',
                sex: '',
                type: null,
                arr: [{

                    name: 'Tom',
                    age: 19,
                    sex: '男'
                }, {

                    name: 'Jone',
                    age: 21,
                    sex: '女'
                }, ],


            }
        },

        methods: {

            addOrEdit() {
                let newObj = {

                    name: this.name,
                    age: this.age,
                    sex: this.sex
                }
                if (this.type == null) {
                    if (!this.name || !this.age || !this.sex) {
                        alert("输入的值不能为空")
                        return
                    }


                    this.arr.push(newObj)
                    this.age = this.sex = this.name = ''
                } else {


                    this.arr.splice(this.type, 1, newObj)
                    this.age = this.sex = this.name = ''
                    this.type = null
                }

            },
            del(i) {
                this.arr.splice(i, 1)
            },
            edit(i) {
                let obj = this.arr[i]
                this.name = obj.name;
                this.age = obj.age;
                this.sex = obj.sex;
                this.type = i
            }
        }
    }
</script>